package com.psjj.privilege.dao;

import com.psjj.privilege.po.Role;
import com.psjj.privilege.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class RoleDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());

    public List<Role> queryAll() throws SQLException {
        List<Role> list = queryRunner.query("select * from t_role order by rid desc",
                new BeanListHandler<Role>(Role.class));
        return list;
    }

    public void add(Role role) throws SQLException {
        queryRunner.update("insert into t_role(rname,description) values(?,?)",role.getRname(),role.getDescription());
    }

    public Role queryRoleById(int rid) throws SQLException {
        Role role = queryRunner.query("select * from t_role where rid=?", new BeanHandler<Role>(Role.class), rid);
        return role;
    }

    public void edit(Role role) throws SQLException {
        queryRunner.update("update t_role set rname=?,description=? where rid=?",
                role.getRname(), role.getDescription(), role.getRid());
    }

    public void del(int rid) throws SQLException {
        queryRunner.update("delete from t_role where rid=?",rid);
    }

    public List<Role> queryRolesByUid(int uid) throws SQLException {
        List<Role> roles = queryRunner.query("select r.* from t_user_role ur, t_role r " +
                        " where ur.roleid=r.rid and ur.userid = ?",
                new BeanListHandler<Role>(Role.class), uid);
        return roles;
    }

    public boolean queryHasUserIdAndRoleId(int uid, Integer rid) throws SQLException {
        Long count = queryRunner.query("select count(*) from t_user_role where userid=? and roleid=?",
                new ScalarHandler<Long>(),
                uid, rid);
        if(count>0){
            return true;
        }else {
            return false;
        }
    }
}
